const rap = {
  config: {
    rapURL: '',
    rapMode: 0,
    rapWhiteList: [],
    rapBlackList: [],
    rapFilterHeaders: ['logintoken', 'termid', 'token'],
    // rapFilterMethods: ['put', 'delete']
    rapFilterMethods: [] // RAP2已支持put、delete
  },
  updateConfig(config) {
    this.config = {
      ...this.config,
      ...config
    };
  },
  convertUrlToRelative(url) {
    let baseUrl;
    if (url instanceof RegExp) {
      return url;
    }
    if (!url) {
      throw Error(`Illegal url:${url}`);
    }
    if (url.indexOf('http://') > -1) {
      baseUrl = url.substring(url.indexOf('/', 7) + 1);
    } else if (url.indexOf('https://') > -1) {
      baseUrl = url.substring(url.indexOf('/', 8) + 1);
    } else {
      baseUrl = url;
    }
    return baseUrl;
  },
  isRap(url) {
    let isRap = false;
    const rapMode = this.config.rapMode;
    if (!rapMode || rapMode === 0) { // disabled
      isRap = false;
    } else if (rapMode === 1) { // intercept all requests
      isRap = true;
    } else if (rapMode === 2 || rapMode === 3) { // black/white list mode
      const blackMode = rapMode === 2;
      isRap = blackMode;
      const list = blackMode ? this.config.rapBlackList : this.config.rapWhiteList;
      for (let i = 0; i < list.length; i += 1) {
        const matchValue = this.convertUrlToRelative(list[i]);
        if ((typeof matchValue === 'string' && (url.indexOf(matchValue) >= 0 || matchValue.indexOf(url) >= 0)) || (typeof matchValue === 'object' && matchValue instanceof RegExp && matchValue.test(url))) {
          // 正则匹配规则最好不要用/g，否则第一次匹配true，第二次匹配false，系lastIndex引起
          isRap = !blackMode;
          break;
        }
      }
    }
    return isRap;
  },
  onFulfilled(temp) {
    const config = temp;
    if (this.isRap(config.url)) {
      config.url = config.url.replace(config.baseURL, this.config.rapURL);
      config.baseURL = this.config.rapURL;
      // 处理RAP上不支持的Header
      if (config.headers && config.headers.common && this.config.rapFilterHeaders.length > 0) {
        this.config.rapFilterHeaders.forEach((value) => { // RAP上不需要Authorization字段，否则报错
          delete config.headers.common[value];
          delete config.headers[value];
        });
      }

      // 处理RAP上不支持的Method
      if (this.config.rapFilterMethods && this.config.rapFilterMethods.length > 0) {
        this.config.rapFilterMethods.forEach((value) => {
          if (config.method === value) {
            config.method = 'post';
          }
        });
      }
    }
    return config;
  },
  onRejected(error) {
    return Promise.reject(error);
  }
};

export default rap;
